package com.weiyirong99.crm.app.ui;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.adapter.PhoneAdapter;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseFragment;
import com.weiyirong99.crm.app.bean.MyBean;
import com.weiyirong99.crm.app.bean.PhoneListBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Fragment01 extends BaseFragment {
    private RecyclerView rl01;
    private SmartRefreshLayout supplierInquirySrlAnnounce;
    private ClassicsHeader classicHeader;
    private ClassicsFooter classicFooter;
    private List<PhoneListBean.ListDTO> phoneList = new ArrayList<>();
    private PhoneAdapter phoneAdapter;
    private int number = 1;
    private LinearLayout llNoData;

    @Override
    public int bindLayout() {
        return R.layout.fragment_01;
    }

    @Override
    public View initView(View view) {
        supplierInquirySrlAnnounce = (SmartRefreshLayout) view.findViewById(R.id.supplier_inquiry_srl_announce);
        classicHeader = (ClassicsHeader) view.findViewById(R.id.classic_header);
        classicFooter = (ClassicsFooter) view.findViewById(R.id.classic_footer);
        rl01 = (RecyclerView) view.findViewById(R.id.rl_01);
        llNoData = (LinearLayout) view.findViewById(R.id.ll_no_data);
        phoneAdapter = new PhoneAdapter(R.layout.item_phone, phoneList);
        rl01.setLayoutManager(new LinearLayoutManager(getActivity()));
        rl01.setAdapter(phoneAdapter);
        supplierInquirySrlAnnounce.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                number++;
                Log.e("WG", "onLoadMore:     " + number);
                getData(number, 0);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Log.e("WG", "onRefresh:     " + number);
                number = 1;
                phoneList.clear();
                getData(number, 1);
            }
        });
//        phoneAdapter.bindToRecyclerView(rl01);

        getData(1, 0);

        phoneAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                PhoneListBean.ListDTO listDTO = phoneList.get(position);
                int id = listDTO.getId();
                Intent intent = new Intent(getActivity(), ClientDetailActivity.class);
                intent.putExtra("customer_id",id);
                getActivity().startActivity(intent);
//                new XPopup.Builder(getContext())
//                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .asBottomList("", new String[]{"客户详情", "填写跟进", "拨打号码"},
//                                null, -1,
//                                new OnSelectListener() {
//                                    @Override
//                                    public void onSelect(int position, String text) {
//                                        Log.e("WG", "onClick: " + text);
//
//
////                                        if (text.equals("客户详情")){
////
////                                        }else if (text.equals("填写跟进")){
////                                            Intent intent = new Intent(getActivity(), AddCustsActivity.class);
////                                            intent.putExtra("customer_id",id);
////                                            getActivity().startActivity(intent);
////                                        }else {
////                                            Intent intent = new Intent(Intent.ACTION_CALL);
////                                            Uri data = Uri.parse("tel:" + listDTO.getMobile());
////                                            intent.setData(data);
////                                            startActivity(intent);
////                                        }
//                                    }
//                                })
//                        .show();
            }
        });
        return view;
    }

    public void getData(int number, int state) {
        long id = MMKV.defaultMMKV().decodeInt("companyId");
        String str = "NEW_CUSTOMER";
        Log.e("WG", "getData: " + id);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("pool", "BIZ");
//        dataMap.put("group", str);
//        dataMap.put("current", number);
        JSONObject jsonObject = new JSONObject(dataMap);
//        http://47.101.46.16:8080/api/company/1/customers/list?listType=MY&group=NEW_CUSTOMER&current=1&pageSize=50
//        OkGo.<String>post(Url.BaseUrl + "/api/company/" + id + "/customers/list?listType=" + str + "&current=" + number + "&=" + 10)
        OkGo.<String>post(Url.BaseUrl + "/api/company/" + id + "/customers/list?listType=MY&group=" + str + "&current=" + number + "&pageSize=" + 10)
                .tag(getContext())
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
                .upJson(jsonObject)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("WG", "onSuccess: " + response.body());
                        if (response.code() == 200) {

                            PhoneListBean phoneListBean = new Gson().fromJson(response.body(), PhoneListBean.class);
                            List<PhoneListBean.ListDTO> list = phoneListBean.getList();

                            if (number==1){
                                if (phoneList.size()>0) {
                                    phoneList.clear();
                                }
                                if (list.size() == 0) {
                                    llNoData.setVisibility(View.VISIBLE);
                                    supplierInquirySrlAnnounce.setVisibility(View.GONE);
                                } else {
                                    llNoData.setVisibility(View.GONE);
                                    supplierInquirySrlAnnounce.setVisibility(View.VISIBLE);
                                }
                            }
                            for (int i = 0; i < list.size(); i++) {
                                phoneList.add(list.get(i));
                            }
                            getLoadMore(state, true);
                            phoneAdapter.notifyDataSetChanged();
                        } else {
                            getLoadMore(state, false);

                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");
                        Toast.makeText(getContext(), response.message(), Toast.LENGTH_LONG).show();
                        getLoadMore(state, false);
                        llNoData.setVisibility(View.VISIBLE);
                        supplierInquirySrlAnnounce.setVisibility(View.GONE);
                    }
                });

    }


    private void getLoadMore(int start, boolean flag) {
        if (start == 1) {
            supplierInquirySrlAnnounce.finishRefresh(flag);
        } else {
            supplierInquirySrlAnnounce.finishLoadMore(flag);
        }
    }

}
